//
//  KBAlbumsDetailViewController.m
//  喜马拉雅改良版框架
//
//  Created by dllo on 15/12/24.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "KBAlbumsDetailViewController.h"
#import "KBSelectedWorks.h"
@interface KBAlbumsDetailViewController ()<UITableViewDataSource, UITableViewDelegate, KBSelectedViewDelegate>

@property (nonatomic, strong)UITableView *myTableView;
@property (nonatomic, strong)NSMutableArray *dataArray; // 大数组
@property (nonatomic, strong)NSMutableArray *albumArray;// Hearder数组
@property (nonatomic, strong)NSMutableArray *tracksArray; // tableView数组

@property (nonatomic, strong)UIView *headerView;// 头部

@property (nonatomic, strong)KBAlbumsHearderView *headView;

@property (nonatomic, strong)KBAlbumsModel *albumsMode;
@property (nonatomic, strong)UIImageView *backgroundImageView;
@property (nonatomic, strong)FXBlurView *blurView; // 毛玻璃
@property (nonatomic, strong)UIImageView *overImage;
@property (nonatomic, copy)NSString *totalCount;

@property (nonatomic, copy)NSString *maxPageId;

@property (nonatomic, strong)KBSelectedWorks *selected;
// tableView后面加一个底 防止毛玻璃bug
@property (nonatomic, strong)UIView *myBackView;
@end

@implementation KBAlbumsDetailViewController
// 设置一进来就隐藏navigationBar
- (void)viewWillAppear:(BOOL)animated
{
//    self.edgesForExtendedLayout = UIRectEdgeNone;//    iOS7及以后的版本支持，self.view.frame.origin.y会下移64像素至navigationBar下方。
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.hidden = YES;
}
// 离开页面时触发, 设置把隐藏的Bar还原,以防进入其他页面时Bar隐藏
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 初始化数组
    _dataArray = [NSMutableArray array];
    
    _currentPage = 1;
    [self createSubViews];
    [self getData];
    
}

- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%ld/20?albumId=%@&isAsc=true&device=iphone&pageSize=20", self.albumId, self.currentPage, self.albumId];
    [AFNetworkTool getUrl:url body:self result:HXJSON headerFile:nil success:^(id result) {
        
        _albumArray = [NSMutableArray array];
        _tracksArray = [NSMutableArray array];
        
        NSMutableDictionary *bigDic = result;
        [_dataArray addObject:bigDic];
#pragma mark - Hearder区域数据
        
        _albumsMode = [[KBAlbumsModel alloc] initWithDictionary:[bigDic objectForKey:@"album"]];
        
        // 背景图
        NSURL *url = [NSURL URLWithString:_albumsMode.coverOrigin];
        [self.backgroundImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:ImagePlaceHolder]];
//        NSLog(@"_aaaa = %@", _albumsMode.coverOrigin);
        
        NSURL *urlOne = [NSURL URLWithString:_albumsMode.coverSmall];
        [self.headView.coverOrigin sd_setImageWithURL:urlOne placeholderImage:[UIImage imageNamed:ImagePlaceHolder]];
        // navigetionBar 的标题
        self.title = self.albumsMode.nickname;
        
        self.headView.titleLabel.text = self.albumsMode.title;
        self.headView.nikename.text = self.albumsMode.nickname;
        self.headView.intro.text = self.albumsMode.intro;
        self.headView.playTimes.text = self.albumsMode.playTimes;
        NSURL *urlImg = [NSURL URLWithString:self.albumsMode.avatarPath];
        [self.headView.avatarPath sd_setImageWithURL:urlImg placeholderImage:[UIImage imageNamed:ImagePlaceHolder]];
        
        
        NSMutableDictionary *tracks = [bigDic objectForKey:@"tracks"];
        NSMutableArray *list = [tracks objectForKey:@"list"];
        // 共?集 用来做标题
        _totalCount = [tracks objectForKey:@"totalCount"];
        _maxPageId = [tracks objectForKey:@"maxPageId"];
        for (NSDictionary *dic in list)
        {
            KBalbumsTableModel *tableModel = [[KBalbumsTableModel alloc]initWithDictionary:dic];
            [_tracksArray addObject:tableModel];
        }
//        NSLog(@"arr = %ld", _tracksArray.count);
        
        // 刷新数据
        [_myTableView reloadData];
        
        self.currentPage ++;
        
    } failure:^(NSError *error) {
        
        NSLog(@"请求失败");
    }];
}
// 布局视图(头)
- (void)createSubViews
{
    // 背景图
    self.backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -250, SCREEN_WIDTH, 250)];
    self.blurView  = [[FXBlurView alloc]init];
    self.blurView.blurRadius = 90;
    // 约束毛玻璃大小跟图片一样(一起动)
    [self.backgroundImageView addSubview:self.blurView];
    self.backgroundImageView.userInteractionEnabled = YES;
    self.blurView.userInteractionEnabled = YES;
    [self.blurView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.equalTo(self.backgroundImageView);
        
    }];
    // 初始化tableView
    _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    [self.view addSubview:_myTableView];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;

    // cell行高
    _myTableView.rowHeight = 60;
    _myTableView.contentInset = UIEdgeInsetsMake(250, 0, 0, 0);
    [self.myTableView addSubview:self.backgroundImageView];
    // 注册
    [_myTableView registerClass:[KBAlbumsTableViewCell class] forCellReuseIdentifier:@"cell"];

    self.headView = [[KBAlbumsHearderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 250)];
    self.headView.backgroundColor = [UIColor clearColor];
    self.headView.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.headView.goBack addGestureRecognizer:self.headView.tap];
    [self.blurView addSubview: self.headView];
}
// 实现轻拍方法 返回上一页面
- (void)tapAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
// tableView Header&&Footer 高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 45;
}
// tableView初始化要写成group,否则会出现BUG
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
// 设置标题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
    headerView.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    UILabel *myLable = [[UILabel alloc]init];
    NSString *str = [NSString stringWithFormat:@"共%@集", _totalCount];
    myLable.text = str;
    myLable.textColor = [UIColor colorWithRed:0.62 green:0.62 blue:0.62 alpha:1];
    myLable.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:myLable];
    [myLable mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(10);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(70);
        
    }];
    // 选集
    UIImageView *lectImage = [[UIImageView alloc] init];
    lectImage.image = [UIImage imageNamed:@"album_segButton@2x.png"];
    [headerView addSubview:lectImage];
    [lectImage mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(myLable).offset(14);
        make.left.equalTo(myLable).offset(220);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(18);
        
    }];
    UIButton *lectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    lectButton.tag = 1000;
    [lectButton setTitle:@"选集" forState:UIControlStateNormal];
    lectButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [lectButton setTitleColor:[UIColor colorWithRed:0.46 green:0.49 blue:0.55 alpha:1] forState:UIControlStateNormal];
    [lectButton addTarget:self action:@selector(lectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:lectButton];
    [lectButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(lectImage);
        make.left.equalTo(lectImage.mas_right).offset(-7);
        make.width.mas_equalTo(55);
        make.height.mas_equalTo(18);
    }];

    // 排序
    UIImageView *sortImage = [[UIImageView alloc] init];
    sortImage.image = [UIImage imageNamed:@"album_sortButton@2x.png"];
    [headerView addSubview:sortImage];
    [sortImage mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(lectImage);
        make.left.equalTo(lectImage.mas_right).offset(60);
        make.width.mas_equalTo(lectImage.mas_width).offset(2);
        make.height.mas_equalTo(lectImage.mas_height);
        
    }];
    
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sortButton setTitle:@" 排序" forState:UIControlStateNormal];
    sortButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [sortButton setTitleColor:[UIColor colorWithRed:0.46 green:0.49 blue:0.55 alpha:1] forState:UIControlStateNormal];
    [sortButton addTarget:self action:@selector(sortBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:sortButton];
    [sortButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(lectButton);
        make.right.equalTo(@-7);
        make.width.mas_equalTo(lectButton);
        make.height.mas_equalTo(lectButton);
        
    }];
    return headerView;
}
#pragma mark - 选集方法
- (void)lectBtnAction:(UIButton *)cender
{
    
    if (cender.selected == NO)
    {
        // 初始化排序View
        _selected = [[KBSelectedWorks alloc] init];
        _selected.SWdelegate = self;
        [self.myTableView addSubview:_selected];
        // 下拉动画
        _selected.maxPageId = _maxPageId.intValue;
        _selected.count = _totalCount.intValue;
        [UIView animateWithDuration:0.5 animations:^{
            
            _selected.frame = CGRectMake(0, 45, SCREEN_WIDTH, SCREEN_HEIGHT-290);
            self.myTableView.scrollEnabled =NO;

            // 取消tableView点击事件
            _myTableView.allowsSelection = NO;
        }];
        NSLog(@"1");
    }
    else if (cender.selected == YES)
    {
        // 下拉动画
        _selected.maxPageId = _maxPageId.intValue;
        [UIView animateWithDuration:0.5 animations:^{
            
            _selected.frame = CGRectMake(SCREEN_WIDTH*2, 45, SCREEN_WIDTH, SCREEN_HEIGHT-290);
            self.myTableView.scrollEnabled =YES;
            // 打开tableView点击事件
            _myTableView.allowsSelection = YES;
            
        }];
        NSLog(@"2");
    }
    cender.selected = !cender.selected;
}
#pragma mark - 协议方法 实现刷新
- (void)selectedDelegate:(NSIndexPath *)indexPath GetData:(NSInteger)maxPageId
{
    _currentPage = maxPageId-indexPath.row;
    
    _selected.maxPageId = _maxPageId.intValue;
    [UIView animateWithDuration:0.5 animations:^{
        
        _selected.frame = CGRectMake(SCREEN_WIDTH*2, 45, SCREEN_WIDTH, SCREEN_HEIGHT-290);
        self.myTableView.scrollEnabled =YES;
        // 打开tableView点击事件
        _myTableView.allowsSelection = YES;
        
    }];
    NSLog(@"3");
    
    [self getData];
}
#pragma mark - 排序方法
- (void)sortBtnAction:(UIButton *)cender
{
    NSMutableArray *array = [NSMutableArray arrayWithArray:_tracksArray];
    _tracksArray = [NSMutableArray array];
    for (NSInteger i = array.count-1; i >= 0; i--)
    {
        [_tracksArray addObject:[array objectAtIndex:i]];
    }
    [self.myTableView reloadData];
}
#pragma mark - tableView协议方法
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tracksArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    KBAlbumsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   // 取消cell点击事件
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    KBalbumsTableModel *model = [_tracksArray objectAtIndex:indexPath.row];
    cell.model = model;
    
    return cell;
}

#pragma mark - scrollView协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    if (y < -250)
    {
        CGRect frame = self.backgroundImageView.frame;
        frame.origin.y = y;
        frame.size.height =  -y;
        self.backgroundImageView.frame = frame;
        if (290+y<0)
        {
            self.blurView.blurRadius = 0;
        }
        else
        {
            self.blurView.blurRadius = 290 + y;
        }
    }
}
// 点击cell跳转方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    KBalbumsTableModel *model = [_tracksArray objectAtIndex:indexPath.row];
    
    LXMusicPlayerVC *playerVC = [[LXMusicPlayerVC alloc] init];
    playerVC.headImageLarge = model.coverLarge;
    playerVC.songId = model.trackId;
    [self presentViewController:playerVC animated:YES completion:^{
        
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
